var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var fs=require('fs');
var  join = require('path').join;
 
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.post('/', function(req,res,next){
	 var form = new multiparty.Form();
	  form.encoding="utf-8";
	 form.maxFilesSize=20*1024*1024;
	 form.uploadDir='./';
	form.parse(req, function(err, fields, files) {
		console.log(err,fields,files)
		if(files){
			console.log(err, fields, files);
			var old=files.file[0].path;
			console.log(old);
			var date=new Date();
			var newF='./public/images/'+date.getTime()+'.png';
			console.log(newF);
			
			var fr=fs.createReadStream(old);
			var fw=fs.createWriteStream(newF);
			fr.pipe(fw);
			fw.on('close',()=>{
				fs.unlinkSync(old);
				res.send(newF);
			})
		}
//		res.send('no');
		
    });
});

router.get('/list', function(req,res,next){
	var fileNames=findSync('./public/images');
	var arr=[];
	for(var i=0;i<fileNames.length;i++){
		arr[i]={};
		arr[i].name=fileNames[i];
	}
	res.send(arr);
})
function findSync(startPath) {
    let result=[];
    function finder(path) {
        let files=fs.readdirSync(path);
        files.forEach((val,index) => {
            let fPath=join(path,val);
            let stats=fs.statSync(fPath);
            if(stats.isDirectory()) finder(fPath);
            if(stats.isFile()) result.push(fPath);
        });
    }
    finder(startPath);
    return result;
}

router.post('/remove', function(req,res,next){
	var str=req.body.load;
	console.log(str);
	fs.unlinkSync(str);
	res.send('delete  '+str);
})

module.exports = router;
